package com.yq.core.service.impl;

import com.yq.api.exception.usr.AddUserException;
import com.yq.api.exception.usr.DeleteUserException;
import com.yq.api.exception.usr.UpdateUserException;
import com.yq.core.dao.UserDao;
import com.yq.core.dto.UserDO;
import com.yq.core.service.UserService;
import com.yq.core.util.DOUtil;
import com.yq.core.util.UserDOUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * Created by yq on 16-5-25.
 */
@Stateless(name = "userService")
public class UserServiceImpl implements UserService {
    @EJB(beanName = "userDao")
    private UserDao userDao;
    @PersistenceContext(unitName = "mallJPAUnit")
    private EntityManager entityManager;

    private static final Log log = LogFactory.getLog(UserServiceImpl.class);

    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public UserDO findUser(Long userId) {
        if(userId == null || userId <= 0){
            log.warn("User id is invalid, can't find a user!");
            return null;
        }
        return entityManager.find(UserDO.class, userId);
    }

    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public UserDO getUser(UserDO userDO) {
        if(userDO == null || StringUtils.isBlank(userDO.getUsername())){
            return null;
        }
        return userDao.getUser(userDO);
    }

    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public List<UserDO> getUserList(UserDO userDO) {
        if(userDO == null){
            log.warn("user object is null, will return null list object");
            return null;
        }
        return userDao.getUserList(userDO);
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public UserDO addUser(UserDO userDO){
        if(userDO == null){
            throw new AddUserException("userDO参数为空，无法创建用户");
        }
        DOUtil.completeUserDateInfo(userDO);
        entityManager.persist(userDO);
        return userDO;
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public UserDO deleteUser(UserDO userDO) {
        if(!hasValidUserId(userDO)){
            log.warn("需要删除的user为空,将不执行任何操作");
            return userDO;
        }
        UserDO userFromDB = entityManager.find(UserDO.class, userDO.getUserId());
        if(userFromDB == null){
            throw new DeleteUserException("查询不到用户信息，无法删除");
        }
        entityManager.remove(userDO);
        return userDO;
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public UserDO updateUser(UserDO userDO) {
        //数据库中已经有的用户
        UserDO originalUser = userDao.getUser(userDO);
        if(!hasValidUserId(originalUser)){
            throw new UpdateUserException("查询不到用户信息，无法修改");
        }
        userDO.setUserId(originalUser.getUserId());
        userDO.setCreateTime(originalUser.getCreateTime());
        DOUtil.completeUserDateInfo(userDO);
        entityManager.merge(userDO);
        return userDO;
    }

    /**
     * 检查User对象是否有合法的userId
     * */
    private boolean hasValidUserId(UserDO userDO){
        return userDO != null && userDO.getUserId() != null && userDO.getUserId() >= 0;
    }
}
